<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="120px">
      <el-form-item label="员工名称">
        <el-input v-model="employee.empName" style="width: 220px" />
      </el-form-item>
      <el-form-item label="员工性别">
        <el-select v-model="employee.gender" style="width: 100px">
          <el-option :value="0" label="女" />
          <el-option :value="1" label="男" />
        </el-select>
      </el-form-item>
      <el-form-item label="员工年龄">
        <el-input v-model="employee.age" style="width: 220px" />
      </el-form-item>
      <el-form-item label="员工电话">
        <el-input v-model="employee.phone" style="width: 220px" />
      </el-form-item>
      <el-form-item label="员工身份证号">
        <el-input v-model="employee.idNo" style="width: 220px" />
      </el-form-item>
      <el-form-item label="员工生日">
        <el-date-picker v-model="employee.birthday" type="date" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" />
      </el-form-item>
      <!-- 员工头像 -->
      <el-form-item label="员工头像">
        <el-upload
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleAvatarError"
          :action="BASE_API+'/admin/employee/upload'"
          :data="UPLOADFILEBIZ"
          :headers="headers"
          name="avatar"
          class="avatar-uploader"
        >
          <img v-if="employee.avatar" :src="employee.avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate()">保存</el-button>
        <el-button v-show="canIdentify" type="success" @click="handleIdentify()">认证</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import emp from '@/api/employee'
import {getToken} from '@/utils/auth' // get token from cookie

export default {
  data() {
    return {
      ISIDENTIFIED: 1,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      headers: {
        'token': getToken()
      },
      UPLOADFILEBIZ: { biz: 'emp_avatar' },
      canIdentify: false, // 是否可用认证按钮
      BASE_API: 'http://localhost:8099',
      // 初始化员工默认数据
      employee: {},
      saveBtnDisabled: false // 保存按钮是否禁用，防止表单重复提交
    }
  },
  // 页面渲染成功
  created() {
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id)
    }
  },
  methods: {
    handleRemove(file) {
      console.log(file)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.employee.avatar
      this.dialogVisible = true
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      if (res.code === 20000) {
        // console.log(res)
        this.employee.avatar = res.data
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error('上传失败 （非0）')
      }
    },
    // 错误处理
    handleAvatarError() {
      console.log('error')
      this.$message.error('上传失败（http失败）')
    },
    // 上传校验
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    saveOrUpdate() {
      // 禁用保存按钮
      this.saveBtnDisabled = true
      if (!this.employee.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },
    fetchDataById(id) {
      emp.getById(id).then(res => {
        this.employee = res.data
        this.canIdentify = this.employee.isIdentify === 0
      })
    },
    // 新增讲师
    saveData() {
      emp.saveEmp(this.employee).then(response => {
        this.$message({
          type: 'success',
          message: '新增成功！'
        })
        this.$router.push({ path: '/employee/list' })
      })
    },
    // 根据id更新记录
    updateData() {
      emp.updateById(this.employee.id, this.employee).then(response => {
        this.$message({
          type: 'success',
          message: '修改成功！'
        })
        this.$router.push({ path: '/employee/list' })
      })
    },
    handleIdentify() {
      this.$confirm('是否已经确认信息无误！', '认证员工', {
        distinguishCancelAndClose: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定认证'
      }).then(() => {
        emp.IdentifyEmpById(this.employee.id, this.ISIDENTIFIED).then(res => {
          this.employee.isIdentify = this.ISIDENTIFIED
          this.fetchDataById(this.employee.id)
          this.$message.success('认证成功！')
        })
      }).catch(action => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
.avatar-uploader .avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409EFF;
}

.avatar-uploader img {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
